 //
//  FindSecondViewController.m
//  FoodList
//
//  Created by 王金晶 on 16/4/7.
//  Copyright © 2016年 王金晶. All rights reserved.
//

#import "FindSecondViewController.h"
#import <UIImageView+WebCache.h>
#import "FindSecondModel.h"
#import "findSecondHeadModel.h"
#import "ingredientModel.h"
#import "FindSecondHeadTableViewCell.h"
#import "FindSecondTableViewCell.h"
#import "IngredientsTableViewCell.h"
#import "RequestManger.h"
#import "headView.h"
#import "CommentModel.h"
#import "CommentTableViewCell.h"
#import "FootView.h"
#import "CommentViewController.h"
@interface FindSecondViewController ()<UITableViewDataSource,UITableViewDelegate,UMSocialUIDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *modelArray;//步骤
@property(nonatomic,strong)NSMutableArray *ingredientArray;//食材
@property(nonatomic,strong)NSMutableArray *mianIngredientArray;//主材
@property(nonatomic,strong)NSMutableArray *commentArray;//评论数组
@property(nonatomic,strong)findSecondHeadModel *model;
@property(nonatomic,strong)headView *headView;
@property(nonatomic,strong)FootView *footView;
@property(nonatomic,assign)CGFloat index;
@property(nonatomic,assign)CGFloat Y;

@end

@implementation FindSecondViewController
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.alpha = 0;
    self.navigationController.navigationBar.translucent = YES;
}
- (void)getData
{   //步骤model和食材model数组
    _modelArray = [NSMutableArray array];
    _ingredientArray = [NSMutableArray array];
    [RequestManger requestWithURL:[NSString stringWithFormat:@"http://www.xdmeishi.com/index.php?m=mobile&c=index&a=getCookbookDetails&id=%@",self.myID] requestType:@"RequestGet" parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //先取头部的model数据
        NSDictionary *dataDic = dic[@"data"];
        _model = [[findSecondHeadModel alloc]init];
        [_model setValuesForKeysWithDictionary:dataDic];
        //装评论数组
        _commentArray = [NSMutableArray array];
        if (![dataDic[@"comments"] isKindOfClass:[NSNull class]]) {
            NSArray *commentsArr = dataDic[@"comments"];
            for (NSDictionary *dic in commentsArr) {
                CommentModel *model = [[CommentModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                NSDictionary *userDic = dic[@"user"];
                [model setValuesForKeysWithDictionary:userDic];
                [_commentArray addObject:model];
            }
        }
         //装食材数组
        NSArray *array = dic[@"data"][@"ingredients"];
        for (NSDictionary *dic in array) {
            ingredientModel *model = [[ingredientModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_ingredientArray addObject:model];
        }
        //装主材料
        _mianIngredientArray = [NSMutableArray array];
        for (ingredientModel *model in _ingredientArray) {
            NSString *string = [NSString stringWithFormat:@"%@",model.isMain];
            if ([string isEqualToString:@"ture"]) {
                [_mianIngredientArray addObject:model];
                [_ingredientArray removeObject:model];
            }
        }
        //装步骤数组
        NSArray *array1 = dic[@"data"][@"makingSteps"];
        for (NSDictionary *dic in array1) {
            FindSecondModel *model = [[FindSecondModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            _headView.name.text = _model.name;
            self.tableView.tableHeaderView = _headView;
            [self.tableView reloadData];

        });
    } error:nil];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.alpha = 0;
    self.navigationItem.title = self.name;
    [self.icon sd_setImageWithURL:[NSURL URLWithString:self.imageURL]];
    
    [self getData];
    
    _headView = [[UINib nibWithNibName:@"headView" bundle:nil]instantiateWithOwner:self options:nil].firstObject;
    _headView.frame = CGRectMake(0, 0, Width, 400);
    [_headView.back addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
    //分享按钮
    [_headView.share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    _headView.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundColor = [UIColor clearColor];
    
    _footView = [[UINib nibWithNibName:@"FootView" bundle:nil]instantiateWithOwner:self options:nil].firstObject;
    _footView.frame = CGRectMake(0, 300, Width, Height- 300);
    [_footView.comment addTarget:self action:@selector(allComment:) forControlEvents:UIControlEventTouchUpInside];
    [_footView.button addTarget:self action:@selector(remind:) forControlEvents:UIControlEventTouchUpInside];
    
    self.tableView.tableFooterView = _footView;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 1000;
    
}
//返回
- (void)back:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}
//分享
- (void)shareAction:(UIButton *)button
{
   [UMSocialSnsService presentSnsIconSheetView:self
    appKey:@"570f35c9e0f55a0d7a0005f8" shareText:@"你要分享的文字"shareImage:[UIImage imageNamed:@"1"]shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,nil] delegate:self];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    else if(section == 1)
    {
        if (_mianIngredientArray.count == 0) {
            return 0;
        }else
        {
            return _mianIngredientArray.count;
        }
    }
    else if(section == 2)
    {
        return _ingredientArray.count;
    }
    
    else if(section == 3){
        return _modelArray.count;
    }
    else
    {
        return _commentArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        FindSecondHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"head"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"FindSecondHeadTableViewCell" owner:nil options:nil]firstObject];
        }
        cell.model = _model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath.section == 1)
    {
        if (_mianIngredientArray.count != 0) {
            IngredientsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ingredient"];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle]loadNibNamed:@"IngredientsTableViewCell" owner:nil options:nil]firstObject];
            
            }
            cell.model = _mianIngredientArray[indexPath.row];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
    }
    else if(indexPath.section == 2)
    {
        IngredientsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ingredient"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"IngredientsTableViewCell" owner:nil options:nil]firstObject];
        }
        cell.model = _ingredientArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    else if(indexPath.section == 3){
        FindSecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"findsecond"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"FindSecondTableViewCell" owner:nil options:nil]firstObject];
        }
        cell.model = _modelArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"comment"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"CommentTableViewCell" owner:nil options:nil].firstObject;
    }
    cell.model = _commentArray[indexPath.row];
    [cell.remind addTarget:self action:@selector(remind:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
//返回分区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        if (_mianIngredientArray.count != 0) {
            return @"主材:";
        }else
        {
            return @"";
        }
        
    }
    else if (section == 2)
    {
        return @"辅料:";
    }
    else if(section == 3)
    {
        return @"步骤:";
    }
    else if (section == 4)
    {   if(_commentArray.count != 0)
    {  _footView.comment.userInteractionEnabled = YES;
        return @"食友评论";
     }else
     {
         _footView.comment.userInteractionEnabled = NO;
         return @"";
     }
    }
        return @"";
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{ if(section == 0)
  {
     return 0;
  }
   else if (section == 1) {
        if (_mianIngredientArray.count == 0) {
            return 0;
        }
    }
    
    return 20;
}

#pragma mark ------------开始滚动会触发的方法--------------------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"%f",scrollView.contentOffset.y);
    if (scrollView.contentOffset.y == 0) {
        _index = 0;
    }
   static CGFloat index1 = 1;
    index1 = index1 + 0.001;
    if(scrollView.contentOffset.y > 0)
    {
    if (scrollView.contentOffset.y > _Y)
    {   //改变图片大小
        [UIView animateWithDuration:0.5 animations:^{
            self.icon.transform = CGAffineTransformMakeScale(index1, index1);
        } completion:nil];
        if (scrollView.contentOffset.y >= 330) {
            self.icon.transform = CGAffineTransformMakeScale(1, 1);
            //重置为1;
            index1 = 1;
        }
        if (scrollView.contentOffset.y > 800) {
            [UIView animateWithDuration:1 animations:^{
                self.icon.frame = CGRectMake(0,300 , Width, Height- 300);
            } completion:nil];
        }
        //说明向上滑动
        _index = _index + 0.03;
        if (_index >= 1)
        {
            _index = 1;
        }
        self.navigationController.navigationBar.alpha = _index;
    }
    else if(scrollView.contentOffset.y < _Y){
        if (scrollView.contentOffset.y ==2000) {
            [UIView animateWithDuration:0.5 animations:^{
               self.icon.frame = CGRectMake(0, 0, Width, Height);
            } completion:^(BOOL finished) {
                
            }];
        }
        //下滑的时候
        if (scrollView.contentOffset.y < 400)
        {
            _index = _index - 0.05;
            if (_index <= 0)
            {
                _index = 0;
            }
            self.navigationController.navigationBar.alpha = _index;
            if (scrollView.contentOffset.y < 10)
            {
                self.navigationController.navigationBar.alpha = 0;
            }
        }
    }
 }
    else
    {
        self.navigationController.navigationBar.alpha = 0;
    }
    _Y = scrollView.contentOffset.y;
}
//跳转到所有评论界面
- (void)allComment:(UIButton *)button
{
    CommentViewController *commentVc = [[CommentViewController alloc]initWithNibName:@"CommentViewController" bundle:nil];
    commentVc.myID = _myID;
    [self.navigationController pushViewController:commentVc animated:YES];
}
//举报
- (void)remind:(UIButton *)button
{
    UIAlertController *control = [UIAlertController alertControllerWithTitle:@"提示" message:@"举报成功" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [control addAction:cancelAction];
    [self presentViewController:control animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
